import type { LoginFormRaw } from '@/types/sys/auth';
/**
 *
 * @returns 获取登录表单
 */
export const useLoginForm = () => {
  const loginForm = reactive<LoginFormRaw>({
    username: 'admin',
    password: '123456',
    captcha: '',
    rememberMe: false
  });

  const loginFormRules: FormRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  };

  return {
    loginForm,
    loginFormRules
  };
};

/**
 *
 * @param formRef 表单实例
 * @param loginForm
 * @returns
 */
export const useHandleLogin = (loginForm: LoginFormRaw) => {
  // 表单引用
  const loginRef = ref<FormInstance>(null);
  const loading = ref(false);

  const router = useRouter();
  const userStore = useUserStore();
  const handleLogin = () => {
    if (!loginRef.value) return;
    loginRef.value.validate((valid: boolean) => {
      if (!valid) return;
      loading.value = true;
      if (loginForm.rememberMe) {
        // todo 添加cookie
      } else {
        // todo 移除cookie
      }

      userStore
        .login(loginForm)
        .then((res) => {
          ElMessage.success('登录成功');
          router.push('/');
        })
        .catch((err) => {
          loading.value = false;
          ElMessage.error(err.message);
        });
    });
  };
  return {
    loginRef,
    loading,
    handleLogin
  };
};
